package com.smartx.app.fragment;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.smartx.Network;
import com.smartx.app.R;
import com.smartx.app.SatApp;
import com.smartx.config.Constants;
import com.smartx.core.Wallet;
import com.smartx.crypto.Hex;
import com.smartx.crypto.Key;
import com.smartx.crypto.bip32.CoinType;
import com.smartx.crypto.bip32.HdKeyPair;
import com.smartx.crypto.bip32.key.KeyVersion;
import com.smartx.crypto.bip39.MnemonicGenerator;
import com.smartx.crypto.bip44.Bip44;

import java.io.File;
import java.io.InputStream;

public class ImportMnemonicFragment extends Fragment implements View.OnClickListener {

    private final static String TAG = "wallet";
    private static final Bip44 BIP_44 = new Bip44();
    public static final KeyVersion KEY_VERSION = KeyVersion.MAINNET;
    public static final CoinType COIN_TYPE = CoinType.SMARTX_SLIP10;
    private EditText mnemonic;
    private EditText password;
    private Button btnImport;

    public static ImportMnemonicFragment create() {
        return new ImportMnemonicFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return LayoutInflater.from(getContext()).inflate(R.layout.fragment_import_mnemonic, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mnemonic = view.findViewById(R.id.mnemonic);
        password = view.findViewById(R.id.password);
        btnImport = view.findViewById(R.id.import_action);
        btnImport.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.import_action:
                importWalletFromMnemonic();
                break;
        }
    }

    private void importWalletFromMnemonic(){
        this.mnemonic.setError(null);
        String phrase = this.mnemonic.getText().toString();
        String password = this.password.getText().toString();
        if (TextUtils.isEmpty(phrase)) {
            this.mnemonic.setError(getString(R.string.error_field_required));
        } else {
            //import mnemonic and set new password
            try {
                InputStream wordStream = getResources().openRawResource(R.raw.english);
                MnemonicGenerator generator = new MnemonicGenerator();
                byte[] seed = generator.getSeedFromWordlist(phrase, Wallet.MNEMONIC_PASS_PHRASE, Wallet.MNEMONIC_LANGUAGE,wordStream);
                wordStream.close();

                HdKeyPair rootKey = BIP_44.getRootKeyPairFromSeed(seed, KEY_VERSION, COIN_TYPE);
                HdKeyPair childKey = BIP_44.getChildKeyPair(rootKey, 0);
                Key key = Key.fromRawPrivateKey(childKey.getPrivateKey().getKeyData());

                //输入密码，创建钱包文件，跳转到显示页面
                createWalletWithPwd(phrase, password, key);

                //返回闪屏页，进入MainActivity
                getActivity().setResult(Activity.RESULT_OK);
                getActivity().onBackPressed();

            } catch (Exception e) {
                Log.e(TAG,"import wallet from mnemonic failed");
                //返回闪屏页
                getActivity().setResult(Activity.RESULT_CANCELED);
                getActivity().onBackPressed();

                return;
            }
        }
    }

    private void createWalletWithPwd(String phrase, String password, Key key) {
        //TODO: 根据是debug还是prd来决定创建MAINNET还是TESTNET
        Wallet wallet = new Wallet(new File(Constants.WalletDataFilePath), Network.TESTNET);
        if (!wallet.unlock(password)) {
            Log.e(TAG,"create wallet failed unlock wallet failed");
            return;
        }

        if(!wallet.flush()){
            Log.e(TAG,"create wallet failed save wallet failed");
            return;
        }
        wallet.addAccount(key);

        //更新账户信息到钱包文件
        wallet.flush();

        Log.i(TAG,"create new wallet address " + key.toAddressString());
        Log.i(TAG,"create new wallet private key " + Hex.encode(key.getPrivateKey()));
        Log.i(TAG,"create new wallet public key " + Hex.encode(key.getPublicKey()));

        //设置全局的SatApp
        SatApp.getInstance().setWallet(wallet);

        //设置当前钱包使用的账户
        SatApp.getInstance().setCoinBase(0);

        //锁住钱包，以后需要的时候再unlock
        wallet.lock();
    }
}